package com.xiaomi.shoppinglist

import androidx.room.Entity
import androidx.room.PrimaryKey
import java.util.*

@Entity(tableName = "shopping_items")
class ShoppingItem(
    @PrimaryKey(autoGenerate = true)
    var id: Long = 0,
    var name: String,
    var isCompleted: Boolean,
    var isRepeatable: Boolean,
    var createTime: Long,
    var completedTime: Long? = null,
    var reminderInterval: Int = 0,
    var reminderUnit: Int = 0 // 0: days, 1: weeks, 2: months, 3: years
) {
    // 检查是否需要再次提醒
    fun shouldRemind(): Boolean {
        if (!isRepeatable || !isCompleted || completedTime == null) {
            return false
        }

        val currentTime = System.currentTimeMillis()
        val nextReminderTime = calculateNextReminderTime()

        return currentTime >= nextReminderTime
    }

    // 计算下一次提醒时间
    private fun calculateNextReminderTime(): Long {
        completedTime?.let {
            val calendar = Calendar.getInstance()
            calendar.timeInMillis = it

            when (reminderUnit) {
                0 -> calendar.add(Calendar.DAY_OF_YEAR, reminderInterval)
                1 -> calendar.add(Calendar.WEEK_OF_YEAR, reminderInterval)
                2 -> calendar.add(Calendar.MONTH, reminderInterval)
                3 -> calendar.add(Calendar.YEAR, reminderInterval)
            }

            return calendar.timeInMillis
        }
        return 0
    }

    // 重置完成状态
    fun resetCompletion() {
        isCompleted = false
        completedTime = null
    }

    override fun toString(): String {
        return "ShoppingItem(id=$id, name='$name', isCompleted=$isCompleted, isRepeatable=$isRepeatable, createTime=$createTime, completedTime=$completedTime, reminderInterval=$reminderInterval, reminderUnit=$reminderUnit)"
    }
}